package com.ffzx.parentweb.interceptor;

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ffzx.commerce.framework.annotation.Permission;
import com.ffzx.commerce.framework.constant.Constant;
import com.ffzx.commerce.framework.utils.JsonMapper;
import com.ffzx.commerce.framework.utils.RedisWebUtils;
import com.ffzx.commerce.framework.vo.ResultVo;

/**
 * 权限验证拦截器
 * @author zhugj
 * @date 2016年1月16日 下午3:28:42
 * @version 1.0
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			return true;
		} 
		
		HandlerMethod hm = (HandlerMethod) handler;
		Permission permission = hm.getMethodAnnotation(Permission.class);
		boolean isPermissioin = false;//权限标识，默认false表示没有权限
		String[] permissions = null;
		if (permission != null) {
			//当前请求方法的权限
			permissions = permission.privilege();
			Set<String> personPermission = RedisWebUtils.getPermission();
			if (permissions != null && permissions.length > 0) {
				for (String permissionStr : permissions) {
					//获取当前用户的权限
					if (personPermission != null && personPermission.size() > 0) {
						for (String item : personPermission) {
							if (permissionStr.equals(item)) {
								isPermissioin = true;
								break;
							}
						}
					}
					if(isPermissioin) {
						//有权限时结束
						break ;
					}
				}
			}
		} else {
			//没添加Permission权限注解的方法，所有登录用户都可以访问
			isPermissioin = true;
		}
		
		//有操作权限
		if (isPermissioin) {
			return isPermissioin;
		} 
		
		//没有操作权限
		//组装访问所需要的权限
		StringBuffer permissionsSB = new StringBuffer();
		if(null != permissions && permissions.length > 0){
			for (String permissionStr: permissions) {
				permissionsSB.append(permissionStr);
				permissionsSB.append("_");
			}
			permissionsSB.deleteCharAt(permissionsSB.length()-1);
		}
		//ajax请求
		if (request.getHeader("accept").indexOf("application/json") > -1 || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
			response.reset();
			response.setContentType("application/json;charset=utf-8");
			
			ResultVo resultVo = new ResultVo();
			resultVo.setInfoStr("没有操作权限！");
			resultVo.setStatus(Constant.RESULT_ERR);
			//resultVo.setInfoData(permissionsSB.toString());
			resultVo.setInfoError(permissionsSB.toString());
			String resultStr = JsonMapper.getInstance().toJson(resultVo);
			
			try {
	        	response.getWriter().print(resultStr);
	        	response.getWriter().flush();
	        } catch (IllegalStateException ise) {  // If getOutputStream() has already been called
	        	try {
					response.getOutputStream().print(resultStr);
					response.getOutputStream().flush();
				} catch (IOException ioe) {
					logger.error("权限处理错误(AuthInterceptor):", ioe);
				}
	        } catch (IOException ioe) {
	        	logger.error("权限处理错误(AuthInterceptor):", ioe);
			}
			return false;
		}else {
			// 返回到登录界面
			response.sendRedirect(request.getContextPath() + "/noRight.do?permissions=" + permissionsSB.toString());
	        return false;
		}
	}
	
}
